package org.wattdepot.cli.command;

import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Prints information about a single sensordata source at the given timestamp.
 * 
 * @author Alex Kan and Kelvin Green
 * @version 2.0
 */
public class WattDepotListSensordataCommand extends WattDepotCommand {
  /**
   * Prints information about a single sensor data source at the given timestamp.
   * 
   * 
   * @param args contains an array of strings created from the user input.
   * @return a string containing daily Sensordata information.
   */
  public String doCommand(String args[]) {
    if (args.length != 4 || 0 != args[2].compareTo("timestamp")) {
      return "Correct format is sensordata {source} timestamp {timestamp}";
    }
    return getSensordata(args);
  }

  /**
   * Gets information about a single sensor data source at the given timestamp.
   * 
   * 
   * @param args contains an array of strings created from the user input.
   * @return a string variable named output containing output from method.
   */
  private String getSensordata(String[] args) {
    String output = ""; // Holds the output that will be returned at the end of the method.
    boolean error = false; // Is set to true when an error occurs.

    XMLGregorianCalendar tstamp = null;
    try {
      tstamp = Tstamp.makeTimestamp(args[3]);
      SensorData sensorData = getClient().getSensorData(args[1], tstamp);
      output += "Tool: ";
      try {
        output += sensorData.getTool() + cr;
      }
      catch (Exception e) {
        error = true;
      }
      output += "Source: ";
      try {
        String[] sSource = sensorData.getSource().split("/");
        output += sSource[sSource.length - 1] + cr;
      }
      catch (Exception e) {
        error = true;
      }
      output += "Properties: ";

      output += getPropertiesList(sensorData);
    }
    catch (MiscClientException mce) {
      return CON_NOT_FOUND;
    }
    catch (NotAuthorizedException nae) {
      error = true;
      // Should never happen.
      if (error) {
        System.out.println("Please contact support");
      }
    }
    catch (ResourceNotFoundException rne) {
      // rne.printStackTrace();
      return RES_NOT_FOUND;
    }
    catch (BadXmlException bxe) {
      error = true;
    }
    catch (Exception e) {
      return "Not a valid timestamp.";
    }

    output += cr;

    return output;
  }

}